import React from "react";
import { message } from "antd";
import { useRef } from "react";
import "@/assets/styles/Login.scss";
import regexEnum from "@/configs/regexEnum";
import url from "@/configs/server";
import { useState } from "react";
import sha256 from "crypto-js/sha256";
import { useNavigate } from "react-router-dom";

export default function Register() {
  const [buttonText, setbuttonText] = useState("发送验证码");
  const emailRef = useRef<HTMLInputElement>(null);
  const codeRef = useRef<HTMLInputElement>(null);
  const nameRef = useRef<HTMLInputElement>(null);
  const pswRef = useRef<HTMLInputElement>(null);

  const navigateTo = useNavigate();

  const startCount = () => {
    let t = 60;
    const y = setTimeout(() => {
      if (t > 0) {
        setbuttonText(t + "s");
        t--;
      } else {
        setbuttonText("发送验证码");
        clearTimeout(y);
      }
    }, 1000);
  };

  const sendValidcode = async () => {
    const a = emailRef.current?.value;
    if (a == "") {
      emailRef.current?.focus();
      emailRef.current?.reportValidity();
    }
    const t = a?.match(regexEnum.EMAIL_SINGLE_REGEX);
    if (!t || t[0] == "") {
      emailRef.current?.focus();
      emailRef.current?.reportValidity();
      message.info("邮箱不能为空或邮箱格式不正确！");
      return;
    }
    try {
      const response = await fetch(
        url.URL + `/user/mailvalid?email=${emailRef.current?.value}`,
        {
          method: "GET",
        }
      );
      const data = await response.json();
      switch (data.code) {
        case 1001:
          emailRef.current?.focus();
          emailRef.current?.reportValidity();
          message.info("邮箱格式不正确！");
          break;
        case 1002:
          message.info("邮件发送失败");
          break;
        case 1003:
          emailRef.current?.focus();
          emailRef.current?.reportValidity();
          message.info("邮箱已被注册！");
          break;
        case 200:
          startCount();
          break;
        default:
          message.info("未知错误");
          break;
      }
    } catch (error) {
      console.log(error);
    }
  };

  const reqRegister = async (e: any) => {
    e.preventDefault();
    if (
      !nameRef.current?.value ||
      nameRef.current?.value.length < 6 ||
      nameRef.current?.value.length > 20
    ) {
      nameRef.current?.focus();
      message.open({
        type: "warning",
        content: "用户名不能少于6个字符，不能多于20个字符",
      });
      return;
    }
    if (
      !pswRef.current?.value ||
      pswRef.current?.value.length < 8 ||
      pswRef.current?.value.length > 20
    ) {
      pswRef.current?.focus();
      message.open({
        type: "warning",
        content: "密码不能少于6个字符，不能多于20个字符",
      });
      return;
    }
    try {
      const m = sha256(pswRef.current?.value).toString();
      const response = await fetch(url.URL + `/user/register`, {
        method: "POST",
        body: JSON.stringify({
          username: nameRef.current?.value,
          password: m,
          validcode: codeRef.current?.value,
          email: emailRef.current?.value,
        }),
      });
      const data = await response.json();
      switch (data.code) {
        case 1004:
          emailRef.current?.focus();
          emailRef.current?.reportValidity();
          message.open({
            type: "warning",
            content: "用户名已被注册！",
          });
          break;
        case 1005:
          emailRef.current?.focus();
          emailRef.current?.reportValidity();
          message.open({
            type: "warning",
            content: "验证码错误！",
          });
          break;
        case 2001:
          PubSub.publish("ChangeMenu", data.to);
          navigateTo(data.to);
          break;
        default:
          message.open({
            type: "warning",
            content: "未知错误",
          });
          break;
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className="Container">
      <div className="box">
        <form
          className="register_form"
          action="http://127.0.0.1:5000/user/register"
          method="post"
        >
          {/* <h2>注册新用户</h2> */}
          <div className="inputBox">
            <input type="text" ref={emailRef} required name="email" />
            <span>邮箱</span>
            <i />
          </div>
          <div className="inputBox">
            <input
              style={{ width: "70%" }}
              type="text"
              required
              name="validcode"
              ref={codeRef}
            />
            <span>验证码</span>
            <i style={{ width: "70%" }} />
            <button
              type="button"
              style={{
                float: "right",
                position: "absolute",
                background: "#45f3ff",
                border: "none",
                outline: "none",
                margin: "3px 5px",
                height: "95%",
                borderRadius: "4px",
                width: "28%",
              }}
              onClick={sendValidcode}
            >
              {buttonText}
            </button>
          </div>
          <div className="inputBox">
            <input type="text" required name="username" ref={nameRef} />
            <span>账号</span>
            <i />
          </div>
          <div className="inputBox">
            <input type="password" required name="password" ref={pswRef} />
            <span>密码</span>
            <i />
          </div>
          <input
            type="submit"
            value="注册"
            style={{ margin: "auto" }}
            readOnly
            onClick={reqRegister}
          />
        </form>
      </div>
    </div>
  );
}
